package com.winchain.provider.expiration.cmd;

import com.shell.bee.persistence.transaction.Transaction;
import com.shell.bee.persistence.transaction.TransactionUtil;
import com.shell.framework.command.CommandContext;
import com.shell.framework.command.ICommand;
import com.winchain.basic.exception.ExtException;
import com.winchain.provider.expiration.po.CbCredit;
import com.winchain.provider.expiration.rx.BillExpirationEvent;
import com.winchain.provider.expiration.service.CbCreditService;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class BillExpCreditAssetCmd implements ICommand<BillExpirationEvent> {
	protected final Log logger = LogFactory.getLog(getClass());
	@Autowired
	private CbCreditService cbCreditService;

	public boolean execute(CommandContext<BillExpirationEvent> context) throws Exception {
		String expDate = ((BillExpirationEvent) context.getSource()).getDate();
		String grpId = ((BillExpirationEvent) context.getSource()).getGrpId();
		List<CbCredit> credits = getSuccessCredits(expDate, grpId);
		for (final CbCredit cbCredit : credits) {
			this.logger.info("��������������������");
			try {
				TransactionUtil.execute(new Transaction() {
					public void doInTransaction() {
						CbCredit credit = BillExpCreditAssetCmd.this.cbCreditService.lockByKey(cbCredit.getCreditId());
						if (("0".equals(credit.getCreditType())) || ("2".equals(credit.getCreditType()))) {
							BillExpCreditAssetCmd.this.cbCreditService.trdQuota(credit);
						}
					}
				}, new int[0]);
			} catch (Exception e) {
				e.printStackTrace();
				this.logger.error(getClass() + "��������", e);
				throw new ExtException(e.getMessage());
			}
		}
		return false;
	}

	private List<CbCredit> getSuccessCredits(String expDate, String grpId) {
		return this.cbCreditService.getBillCredits(expDate, grpId, "1", null);
	}
}
